/**
 * 日志级别枚举
 */
export enum LogLevel {
  DEBUG = 'debug',
  INFO = 'info',
  WARN = 'warn',
  ERROR = 'error'
}

/**
 * 日志工具类
 */
class Logger {
  private static instance: Logger;
  private readonly isDebug: boolean;
  private readonly isProduction: boolean;
  private readonly logLevel: LogLevel;

  private constructor() {
    this.isDebug = import.meta.env.VITE_DEBUG_MODE === 'true';
    this.isProduction = import.meta.env.MODE === 'production';
    this.logLevel = (import.meta.env.VITE_LOG_LEVEL as LogLevel) || LogLevel.INFO;
  }

  public static getInstance(): Logger {
    if (!Logger.instance) {
      Logger.instance = new Logger();
    }
    return Logger.instance;
  }

  /**
   * 获取日志级别对应的数值
   */
  private getLogLevelValue(level: LogLevel): number {
    const levels = {
      [LogLevel.DEBUG]: 0,
      [LogLevel.INFO]: 1,
      [LogLevel.WARN]: 2,
      [LogLevel.ERROR]: 3
    };
    return levels[level];
  }

  /**
   * 检查是否应该输出日志
   */
  private shouldLog(level: LogLevel): boolean {
    // 开发环境显示所有日志
    if (!this.isProduction) {
      return true;
    }
    
    // 生产环境根据日志级别判断
    return this.getLogLevelValue(level) >= this.getLogLevelValue(this.logLevel);
  }

  /**
   * 格式化日志消息
   */
  private formatMessage(module: string, message: string): string {
    return `[${module}] ${message}`;
  }

  /**
   * 调试日志
   */
  public debug(module: string, message: string, data?: any): void {
    if (this.shouldLog(LogLevel.DEBUG)) {
      console.log(this.formatMessage(module, message), data ? data : '');
    }
  }

  /**
   * 信息日志
   */
  public info(module: string, message: string, data?: any): void {
    if (this.shouldLog(LogLevel.INFO)) {
      console.info(this.formatMessage(module, message), data ? data : '');
    }
  }

  /**
   * 警告日志
   */
  public warn(module: string, message: string, data?: any): void {
    if (this.shouldLog(LogLevel.WARN)) {
      console.warn(this.formatMessage(module, message), data ? data : '');
    }
  }

  /**
   * 错误日志
   */
  public error(module: string, message: string, error?: unknown): void {
    if (this.shouldLog(LogLevel.ERROR)) {
      console.error(this.formatMessage(module, message), error ? error : '');
    }
  }
}

export const logger = Logger.getInstance(); 